import storage from "../utils/storage";

// 导出

export default {
  saveUserInfo(state, userInfo) {
    storage.setItem("userInfo", userInfo);
    state.userInfo = userInfo;
  },
  // 退出操作,清除用户信息
  removeUserInfo(state) {
    storage.clearAll();
    state.userInfo = "";
    // storage.clearItem("userInfo");
  },
   changeItemToCart(state, payLoad) {
      const { shopId, itemId, shopName, itemInfo, num } = payLoad
      // 判断有没有shopId
      let shopInfo = {}
      if (state.cartData[shopId]) {
        shopInfo = state.cartData[shopId]
      } else {
        shopInfo.shopName = shopName
        shopInfo.itemList = {}
      }

      // 判断有没有itemId
      let item = null
      if (shopInfo.itemList[itemId]) {
        item = shopInfo.itemList[itemId]
      } else {
        item = itemInfo
        item.count = 0
      }
      // 数量加减1

      item.count += num
      // 如果为空,则从购物车中移除
      if (item.count === 0) {
        delete shopInfo.itemList[itemId]
      } else {
        item.checked = true
        shopInfo.itemList[itemId] = item
      }
      if (JSON.stringify(shopInfo.itemList) !== '{}') {
        state.cartData[shopId] = shopInfo
      } else {
        delete state.cartData[shopId]
      }
      setLocalCartData(state)
    },
    changeItemChecked(state, payLoad) {
      const { shopId, itemId } = payLoad
      const item = state.cartData[shopId].itemList[itemId]
      item.checked = !item.checked
      setLocalCartData(state)
    },

    setAllChecked(state, payLoad) {
      let { shopId, allChecked } = payLoad
      const shopInfo = state.cartData[shopId].itemList
      if (allChecked) {
        allChecked = false
        for (const key in shopInfo) {
          shopInfo[key].checked = false
        }
      } else {
        for (const key in shopInfo) {
          shopInfo[key].checked = true
        }
        allChecked = true
      }
      setLocalCartData(state)
    }
};
